package com.ruoyi.framework.interceptor

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.annotation.RepeatSubmit
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.utils.ServletUtils.renderString
import org.springframework.stereotype.Component
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 防止重复提交拦截器
 *
 * @author ruoyi
 */
@Component
abstract class RepeatSubmitInterceptor : HandlerInterceptor {
    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        return if (handler is HandlerMethod) {
            val method = handler.method
            val annotation = method.getAnnotation(RepeatSubmit::class.java)
            if (annotation != null) {
                if (isRepeatSubmit(request, annotation)) {
                    val ajaxResult = AjaxResult.error(annotation.message)
                    renderString(response, JSON.toJSONString(ajaxResult))
                    return false
                }
            }
            true
        } else {
            true
        }
    }

    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request 请求信息
     * @param annotation 防重复注解参数
     * @return 结果
     * @throws Exception
     */
    abstract fun isRepeatSubmit(request: HttpServletRequest?, annotation: RepeatSubmit?): Boolean
}
